const socket = io();

// DOM元素
const messages = document.getElementById('messages');
const messageInput = document.getElementById('messageInput');
const sendBtn = document.getElementById('sendBtn');

// 从 localStorage 获取用户名
const username = localStorage.getItem('username');
if (!username) {
  // 如果没有登录，重定向到登录页
  window.location.href = '/login';
}

// 连接后自动加入聊天室
socket.on('connect', () => {
  socket.emit('join', username);
});

// 发送消息
sendBtn.addEventListener('click', sendMessage);
messageInput.addEventListener('keypress', (e) => {
  if (e.key === 'Enter') {
    sendMessage();
  }
});

function sendMessage() {
  const message = messageInput.value.trim();
  if (message) {
    socket.emit('message', message);
    messageInput.value = '';
  }
}

// 接收消息
socket.on('message', (data) => {
  const messageElement = document.createElement('div');
  messageElement.classList.add('message');
  
  const content = document.createElement('div');
  content.classList.add('message-content');
  content.textContent = typeof data === 'string' ? data : `${data.nickname}: ${data.message}`;
  
  const time = document.createElement('div');
  time.classList.add('message-time');
  time.textContent = data.timestamp || new Date().toLocaleString('zh-CN', {
    hour12: false,
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
  
  messageElement.appendChild(content);
  messageElement.appendChild(time);
  messages.appendChild(messageElement);
  messages.scrollTop = messages.scrollHeight;
});

// 自动聚焦输入框
messageInput.focus();
